import scala.actors._

/**
 * Queue takes Passengers and their Bags and sends them to the Bag and Body
 * Scans.
 * @author Samuel Nelson, Robert Vrooman, James Fitzgerald, Gabriel Marcano
 */
class Queue(lineNum: Int, bagScan: BagScan, bodyScan: BodyScan) extends Actor {
  def act() {
    loop {
      react {
        case passenger: Passenger => {
            // Passenger entered the queue. Send the passenger to body check
            // and bag to bag check
            println("Queue " + lineNum + " received Passenger " +
                    passenger.ID + ".")
            
            println("Queue " + lineNum + " is sending Passenger " + passenger.ID
                    + " to BodyScan " + bodyScan.lineNumber + ".")
            bodyScan ! passenger
            println("Queue " + lineNum + " is sending Bag " + passenger.bag.ID
                    + " to BagScan " + bagScan.lineNumber + ".")
            bagScan ! passenger.bag
          }

        case Startup => {
            println("Queue " + lineNum + " received Startup.")
            println("Queue " + lineNum + " is sending Startup to BagScan "
                + bagScan.lineNumber + ".")
            bagScan ! Startup
            println("Queue " + lineNum + " is sending Startup to BodyScan "
                + bodyScan.lineNumber + ".")
            bodyScan ! Startup
          }

        case Shutdown => {
            println("Queue " + lineNum + " received Shutdown.")
            shutdownRequested
          }
      }
    }
  }

  // reactWithin(0) gives a TIMEOUT as soon as the mailbox is empty
  def shutdownRequested: Nothing = reactWithin(0) {
    case Shutdown => {
        shutdownRequested
      }
    case TIMEOUT => {
        println("Queue " + lineNum + " is sending Shutdown to BagScan "
                + bagScan.lineNumber + ".")
        bagScan ! Shutdown
        println("Queue " + lineNum + " is sending Shutdown to BodyScan "
                + bodyScan.lineNumber + ".")
        bodyScan ! Shutdown
        println("Queue " + lineNum + " has now shutdown.")
        exit
      }
  }
}